package com.xgr.wonderful.adapter;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xgr.wonderful.MyApplication;
import com.xgr.wonderful.R;
import com.xgr.wonderful.activity.ChatActivity;
import com.xgr.wonderful.activity.CommentActivity;
import com.xgr.wonderful.activity.GalleryActivity;
import com.xgr.wonderful.activity.PersonalCenterActivity;
import com.xgr.wonderful.constant.Constant;
import com.xgr.wonderful.db.DatabaseUtil;
import com.xgr.wonderful.entity.Photo;
import com.xgr.wonderful.entity.Status;
import com.xgr.wonderful.entity.SuperConversation;
import com.xgr.wonderful.entity.User;
import com.xgr.wonderful.sns.SharePopWindow;
import com.xgr.wonderful.utils.DisplayUtils;
import com.xgr.wonderful.utils.HttpProxy;
import com.xgr.wonderful.utils.LocalLikeRelationsUtils;
import com.xgr.wonderful.utils.LocalUserUtils;
import com.xgr.wonderful.utils.LogUtils;
import com.xgr.wonderful.utils.ToastFactory;
import com.xgr.wonderful.utils.HttpProxy.IHttpRequestListener;
import com.xgr.wonderful.view.CircleImageView;

public class PersonalCenterAdapter extends BaseContentAdapter<Status> {

	private String TAG = "PersonalCenterAdapter" ;
	
	private Activity activity ;
	private final int TYPE_COUNT = 2;
	private final int FIRST_TYPE =0;
	private final int OTHER_TYPE =1 ;
	
	private User mUser ;
	
	private Animation scaleAnimation ;
	
	private int currentType  ;
	public PersonalCenterAdapter(Context context, List<Status> list, User user) {
		super(context, list);
		activity = (Activity)context ;
		this.mUser = user ;
		scaleAnimation = AnimationUtils.loadAnimation(context, R.anim.scale_anim) ;
	}
	
	@Override
	public int getCount() {
		if (mUser!= null){
			if (dataList!= null && dataList.size()!= 0){
				return dataList.size()+1;
			}else {
				return 1;
			}
		}
		LogUtils.i(TAG, "user= null in PersonCenterAdapter") ;
		return 0;
		
	}
	
	@Override
	public Status getItem(int position) {
		if (position!=0){
			if (dataList != null && dataList.size()!= 0){
				return dataList.get(position-1); //减一个
			}else {
				return null;
			}
		}else {
			return null;
		}
		
	}
	
	@Override
	public int getViewTypeCount() {
		return TYPE_COUNT;
	}
	
	@Override
	public int getItemViewType(int position) {
		if (position == 0) {
			return FIRST_TYPE;// 第一种视图
		} else {
			return OTHER_TYPE;
		}
	}

	@Override
	public View getConvertView(int position, View convertView, ViewGroup parent) {
		View personalView = null ;
		View statusView = null ;
		currentType = getItemViewType(position) ;
		
		LogUtils.i(TAG, "position:"+ position) ;
		switch (currentType) {
		case FIRST_TYPE:
			personalView = convertView ;
			PersonalHolder personalHolder = null;
			if (personalView == null){
				personalView = mInflater.inflate(
						R.layout.item_personal_header, null);
				personalHolder = new PersonalHolder();
				personalHolder.mAvatar = (CircleImageView)personalView.
						findViewById(R.id.personal_avatar);
				personalHolder.mUsername = (TextView)personalView.
						findViewById(R.id.personal_name);
				personalHolder.mChatBtn = (Button)personalView.
						findViewById(R.id.personal_chatbtn);
				personalHolder.mTips = (TextView)personalView.
						findViewById(R.id.personal_tips_tv) ;
				personalView.setTag(personalHolder);
			}else {
				personalHolder = (PersonalHolder)personalView.getTag() ;
			}
			//
			handlePersonalView(mUser, position, personalHolder) ;
			convertView = personalView ;
			break;
		case OTHER_TYPE:
			statusView = convertView ;
			StatusHolder statusHolder = null ;
			if (statusView==null){
				statusView = mInflater.inflate(
						R.layout.item_status_homepage1, null);
				statusHolder = new StatusHolder();
				// 不显示头像
				statusHolder.mAvatar = (CircleImageView) statusView.
						findViewById(R.id.item_homepage_userphoto) ;
				statusHolder.mAvatar.setVisibility(View.GONE) ;
				statusHolder.mUsername = (TextView)statusView.
						findViewById(R.id.item_homepage_username);
				statusHolder.mDistance= (TextView)statusView.
						findViewById(R.id.item_homepage_distance);
				statusHolder.mTime = (TextView)statusView.
						findViewById(R.id.item_homepage_time);
				
				statusHolder.mImage = (ImageView)statusView.
						findViewById(R.id.item_homepage_image);
				statusHolder.mContent = (TextView)statusView.
						findViewById(R.id.item_homepage_content);
				
				//comment
				statusHolder.mCommentLL=(LinearLayout) statusView
						.findViewById(R.id.item_homepage_comment);
				statusHolder.mCommentTv= (TextView)statusView
						.findViewById(R.id.item_homepage_comment_tv) ;
				//like 
				statusHolder.mLikeLL = (LinearLayout)statusView
						.findViewById(R.id.item_homepage_like);
				statusHolder.mLikeImg= (ImageView)statusView
						.findViewById(R.id.item_homepage_like_img);
				statusHolder.mLikeTv= (TextView)statusView
						.findViewById(R.id.item_homepage_like_tv) ;
				//share
				statusHolder.mShareLL = (LinearLayout)statusView
						.findViewById(R.id.item_homepage_share) ;
				
				statusView.setTag(statusHolder);
			}else {
				statusHolder = (StatusHolder)statusView.getTag();
			}
			//
			handleStatusView(getItem(position), position, statusHolder) ;
			convertView= statusView;
			break ;

		default:
			break;
		}
		return convertView ;
	}
	
	private void handlePersonalView(final User user, int position,
			PersonalHolder personalHolder) {
		personalHolder.mUsername.setText(user.getUsername()) ;
		//avater
		ImageLoader.getInstance().displayImage(
				user.getPhoto()!= null ? user.getPhoto().getSmall(): null, 
				personalHolder.mAvatar,
				MyApplication.getInstance().getOptions(R.drawable.user_icon_default)) ;
		//如果 是自己的个人中心，则不显示聊天 的按钮 
		//错误的比较，两个都是Integer，类似 String 
		//引用类型（复合类型）的比较 ==比较的是引用（内存地址）
		if (user.getID().intValue()!= LocalUserUtils.getInstance().getLocalUserID()){
			personalHolder.mChatBtn.setVisibility(View.VISIBLE) ;
			personalHolder.mChatBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					SuperConversation superConversation = new SuperConversation(
							user.getID(), user.getUsername(), user.getPhoto()) ;
					//加入到conversationList中去，但是应该再保存一下
					DatabaseUtil.getInstance().addConversation(user.getID(), superConversation ) ;
					DatabaseUtil.getInstance().saveConversationList() ;
					Intent intent = new Intent() ;
					intent.putExtra("data" , user) ;
					intent.setClass(mContext, ChatActivity.class) ;
					activity.startActivity(intent) ;
				}
			}) ;
		}else {
			personalHolder.mChatBtn.setVisibility(View.GONE) ;
			personalHolder.mTips.setText("我发表的") ;
		}
	}
	/**
	 * 下面的将不显示头像，微信也是这样的
	 * @param item
	 * @param position
	 * @param statusHolder
	 */
	private void handleStatusView(final Status curStatus,int position,
			final StatusHolder viewHolder) {
		if (curStatus.getUser() != null){
			viewHolder.mUsername.setText(curStatus.getUser().getUsername()+"");
		}
//		ImageLoader.getInstance().displayImage(
//				curStatus.getUser().getPhoto()!= null ? curStatus.getUser().getPhoto().getSmall() : null ,
//						viewHolder.mAvatar,
//						MyApplication.getInstance().getOptions(R.drawable.user_icon_default) ,
//								new SimpleImageLoadingListener()) ;
		//time 
		viewHolder.mTime.setText(DisplayUtils.transformTime(curStatus.getTime())) ;
		//distance 
		if (curStatus.getDistance()!= null){
			viewHolder.mDistance.setVisibility(View.VISIBLE) ;
			viewHolder.mDistance.setText(DisplayUtils.transformDistance(curStatus.getDistance())) ;
		}else {
			viewHolder.mDistance.setVisibility(View.GONE) ;
		}
		//content 
		if (curStatus.getContent()!= null && curStatus.getContent().length()>0){
			viewHolder.mContent.setVisibility(View.VISIBLE) ;
			viewHolder.mContent.setText(curStatus.getContent()+"") ;
		}else {
			viewHolder.mContent.setVisibility(View.GONE) ;
		}
		// image 
		final List<Photo> imageList = curStatus.getImageurl() ;
		if (null != imageList && imageList.size()!= 0 && imageList.get(0)!= null
				&& imageList.get(0).getUrl()!= null){
			viewHolder.mImage.setVisibility(View.VISIBLE) ;
			ImageLoader.getInstance().displayImage(
					imageList.get(0).getUrl(), 
					viewHolder.mImage ,
					MyApplication.getInstance().getOptions(R.drawable.bg_pic_loading)) ;
		}else {
			viewHolder.mImage.setVisibility(View.GONE) ;
		}
		//like 
		curStatus.setIsLiked(LocalLikeRelationsUtils.getInstance().isLiked(curStatus.getId())) ;
		viewHolder.mLikeTv.setText(curStatus.getUp()+"");
		if (curStatus.getIsliked()){
			viewHolder.mLikeImg.setImageResource(R.drawable.timeline_icon_liked);
		}else {
			viewHolder.mLikeImg.setImageResource(R.drawable.timeline_icon_unlike);
		}
		//comment 
		viewHolder.mCommentTv.setText(curStatus.getCommentnum()+"") ;
		//clik on avatar, goto personal center
		viewHolder.mAvatar.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent () ;
				intent.setClass(mContext, PersonalCenterActivity.class) ;
				intent.putExtra("data", curStatus.getUser()) ;
				activity.startActivity(intent) ;
			}
		}) ;
		//click on image, goto comment,but now is for test
		viewHolder.mImage.setOnClickListener(new OnClickListener() {	
			@Override
			public void onClick(View v) {
				Intent intent = new Intent () ;
				intent.setClass(mContext, GalleryActivity.class) ;
				intent.putExtra("data",  curStatus) ;
				activity.startActivity(intent) ;
			}
		}) ;
		
		//share 
		viewHolder.mShareLL.setOnClickListener(new OnClickListener() {	
			@Override
			public void onClick(View v) {
				String targetUrl = Constant.SHARE_OFFICIAL_URL+"/p.html?id="+curStatus.getId() ;
				String imageUrl = null ;
				if (imageList != null && imageList.size()!=0 && imageList.get(0)!=null
						&& imageList.get(0).getUrl()!= null){
					imageUrl = imageList.get(0).getUrl() ;
				}
				
				SharePopWindow mShare = new SharePopWindow(mContext,
						curStatus.getContent(),
						Constant.SHARE_TITLE, 
						targetUrl,
						imageUrl, 
						null) ;
				mShare.showAtLocation(activity.getWindow()
						.getDecorView(), Gravity.BOTTOM, 0, 0);
			}
		}) ;
		//comment,not completed
		viewHolder.mCommentLL.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent() ;
				intent.putExtra("data", curStatus) ; 
				intent.setClass(activity,CommentActivity.class) ;
				activity.startActivity(intent) ;
			}
		}) ;
		// like 
		viewHolder.mLikeLL.setOnClickListener(new OnClickListener() {	
			@Override
			public void onClick(View v) {
				doLikeClick(viewHolder , curStatus); 
				viewHolder.mLikeImg.startAnimation(scaleAnimation) ;
			}
		}) ;
		
	}

	protected void doLikeClick(final StatusHolder viewHolder, final Status curStatus) {
		if (curStatus.getIsliked()){
			ToastFactory.getToast(mContext,"已经点赞过了").show();
			return ;
		}
		Status temp = new Status(mUser.getID(), curStatus.getId()) ;
		String statusJson = new Gson().toJson(temp) ;
		HttpProxy httpProxy = new HttpProxy() ;
		
		httpProxy.doLikeAction(statusJson, new IHttpRequestListener() {
			
			@Override
			public void OnHttpRequestSuccessful(String result, int errCode) {
				LogUtils.i(TAG, "result:"+result) ;
				if (errCode== Constant.ERR_HTTP_REQUEST_SUCCESS){
					ToastFactory.getToast(mContext, "点赞成功").show() ;
					curStatus.increaseUp() ; //refresh local status list 
					LocalLikeRelationsUtils.getInstance().addLikeRelations(curStatus.getId()) ;
					//立即保存
					LocalLikeRelationsUtils.getInstance().saveLikeRelations();
					LogUtils.i(TAG, "set color for text:"+ curStatus.getUp());
					viewHolder.mLikeImg.setAnimation(scaleAnimation) ;
					viewHolder.mLikeTv.setText(curStatus.getUp()+"") ;//一定要加""
					notifyDataSetChanged() ;
				}else if (errCode == Constant.ERR_HTTP_REQUEST_FAILURE) {
					//参数 错误的中在上面已经排除了
					ToastFactory.getToast(mContext, "点赞失败 result:"+result).show();
				}
			}
			
			@Override
			public void OnHttpRequestStart() {
	
			}
			
			@Override
			public void OnHttpRequestFailure(String info) {
				ToastFactory.getToast(mContext, "点赞失败").show() ;
			}
		}) ;
		
		
	}

	private class PersonalHolder{
		private TextView mUsername ;
		private CircleImageView mAvatar ;
		private Button mChatBtn ;
		//private LinearLayout mTipsL;
		private TextView mTips;
	}
	/**
	 * 不再显示头像
	 * @author lsj
	 *
	 */
	private class StatusHolder {
		private TextView mTime ;
		private TextView mDistance ;
		private TextView mContent ;
		private ImageView mImage;
	
		private TextView mUsername ;
		private CircleImageView mAvatar ;
		
		//like 
		private LinearLayout mLikeLL;
		private TextView mLikeTv;
		private ImageView mLikeImg;
		//share
		private LinearLayout mShareLL;
		//comment
		private LinearLayout mCommentLL;
		private TextView mCommentTv;
		
	}

}
